package com.androidified.personalshopper.model;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.location.Location;

import com.androidified.personalshopper.Constants;
import com.androidified.personalshopper.bean.Commerce;
import com.androidified.personalshopper.bean.CommerceResponse;
import com.androidified.personalshopper.bean.CommercesResponse;
import com.androidified.personalshopper.bean.PromotionsResponse;
import com.androidified.personalshopper.client.CommerceService;
import com.androidified.personalshopper.client.PromotionService;
import com.google.gson.reflect.TypeToken;
import com.littlefluffytoys.littlefluffylocationlibrary.LocationInfo;

public class CommerceModel {

	private static final int DISTANCE_THRESHOLD = 100;
	private static final long ONE_DAY_IN_SECONDS = 24 * 60 * 60;
	
	public static boolean shouldUpdate(LocationInfo lastEvent, LocationInfo event) {
		if (event.getTimestampAgeInSeconds() > ONE_DAY_IN_SECONDS) {
			return true;
		}
		float[] results = new float[1];
		Location.distanceBetween(lastEvent.lastLat, lastEvent.lastLong, event.lastLat, event.lastLong, results);
		return results[0] > DISTANCE_THRESHOLD;
	}
	
	public static List<Commerce> getNearRest(double lat, double lng, int radius) {
		List<Commerce> commerces = null;
		
		CommercesResponse cr = CommerceService.searchNear(Constants.API_KEY, Constants.TEST_TOKEN, lat, lng, radius);
		if (cr != null && cr.getData() != null) {
			commerces = new ArrayList<Commerce>();
			final int count = cr.getData().length;
			for (int i = 0; i < count; i++) {
				CommerceResponse r = CommerceService.get(Constants.API_KEY, Constants.TEST_TOKEN, cr.getData()[i]);
				PromotionsResponse pr = PromotionService.get(Constants.API_KEY, Constants.TEST_TOKEN, r.getData());
				r.getData().setPromotions(pr.getData());
				commerces.add(r.getData());
			}
		}
		
		return commerces;
	}
	
	public static List<Commerce> getCache(Context context) {
	    final Type listType = new TypeToken<ArrayList<Commerce>>() {}.getType();
		return CacheModel.retrieve(context, Constants.COMMERCE_CACHE, listType);
	}
	
	public static boolean storeCache(Context context, List<Commerce> content) {
		return CacheModel.store(context, Constants.COMMERCE_CACHE, content);
	}
	
}
